//
//  walletViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/7/19.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "walletViewController.h"
#import "walletTableViewCell.h"

static NSString *CellIdentifier = @"walletTableViewCell";

@interface walletViewController ()
<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UILabel *moneyLabel;
@property (strong, nonatomic) IBOutlet UIButton *withdrawalButton;
@property (strong, nonatomic) IBOutlet UILabel *withdrawalLabel;
@property (strong, nonatomic) NSMutableArray *tableViewArray;

@end

@implementation walletViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.isWithdrawal) {
        _withdrawalButton.hidden = NO;
        _withdrawalLabel.hidden = NO;
    } else {
        _withdrawalButton.hidden = YES;
        _withdrawalLabel.hidden = YES;
    }
    
    [self wallet];
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _tableViewArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [self.tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
}

#pragma mark - 返回
- (IBAction)Back:(id)sender {
    [self backBtn];
}

#pragma mark - 我的钱包
- (void)wallet {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_queryMemberMuseEpurseInfoById withHttpType:@"POST" withTag:JY_JY_queryMemberMuseEpurseInfoById];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self ConsumptionForRecord];
        });
        
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    
    if (_tableViewArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self ConsumptionForRecord];
        });
    }
    
}


#pragma mark - 电子钱包消费/获得记录
- (void)ConsumptionForRecord {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_queryMemberEpurseFlowList withHttpType:@"POST" withTag:JY_JY_queryMemberEpurseFlowList];
}



#pragma mark - 充值
- (IBAction)topup:(id)sender {
    UIStoryboard *secondStroyBoard = [UIStoryboard storyboardWithName:@"PersonalStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AddMoney"];
    [[Common getNavigation]pushViewController:page];
}

#pragma mark - 提现
- (IBAction)withdrawal:(id)sender {
    UIStoryboard *secondStroyBoard = [UIStoryboard storyboardWithName:@"PersonalStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"withdrawal"];
    [[Common getNavigation]pushViewController:page];
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableViewArray.count;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    walletTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell= [[walletTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    NSString *meflRemark = [NSString stringWithFormat:@"%@",self.tableViewArray[indexPath.row][@"meflRemark"]];
    NSString *meflAmount = [NSString stringWithFormat:@"%@",self.tableViewArray[indexPath.row][@"meflAmount"]];
    NSString *integralRecordStr = [NSString stringWithFormat:@"%@%@元",meflRemark,meflAmount];
    
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:integralRecordStr];
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.965 green:0.639 blue:0.145 alpha:1.000] range:NSMakeRange(integralRecordStr.length - meflAmount.length-1, meflAmount.length)];
    
    [cell.label setAttributedText:noteStr];
    
    cell.timeLabel.text = [NSString stringWithFormat:@"%@",self.tableViewArray[indexPath.row][@"meflCreateTime"]];
    
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==JY_JY_queryMemberMuseEpurseInfoById) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            if ([database[@"result"][@"museEpurse"]isEqual:[NSNull null]]) {
                _moneyLabel.text = @"0.00";
            }else{
                _moneyLabel.text = [NSString stringWithFormat:@"%.2f",[database[@"result"][@"museEpurse"]floatValue]];
            }
        }
    } else if (tag==JY_JY_queryMemberEpurseFlowList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.tableViewArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.tableViewArray addObject:entity];
                }
                [_tableView reloadData];
                
            });
        }
    }

}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
}


@end
